package com.gerryrun.lib_skin;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.LayoutInflaterCompat;

import java.lang.reflect.Field;
import java.util.Observable;
/**
 * @author GerryRun
 * @data 2021/1/27
 * @email gerryin@163.com
 * @describe lifeCycle 实现类
 */
public class ApplicationActivityLifeCycle implements Application.ActivityLifecycleCallbacks {
    private Observable observable;
    private ArrayMap<Activity, SkinLayoutInflateFactory> mLayoutInflateFactories = new ArrayMap<>();

    public ApplicationActivityLifeCycle(Observable observable) {
        this.observable = observable;
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

        LayoutInflater layoutInflater = activity.getLayoutInflater();

        try {
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(layoutInflater, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        SkinLayoutInflateFactory inflateFactory = new SkinLayoutInflateFactory(activity);
        LayoutInflaterCompat.setFactory2(layoutInflater, inflateFactory);
        mLayoutInflateFactories.put(activity, inflateFactory);
        observable.addObserver(inflateFactory);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        SkinLayoutInflateFactory factory = mLayoutInflateFactories.remove(activity);

        SkinManager.init(activity.getApplication()).deleteObserver(factory);
//        observable.deleteObservers();
    }
}
